﻿namespace ResourceFrame
{
    public abstract class Singleton<T> where T : Singleton<T>, new()
    {
        private static T _instance = null;

        // 多线程安全机制
        private static readonly object _locker = new object();

        public static T Instance
        {
            get
            {
                lock (_locker)
                {
                    if (_instance == null)
                    {
                        _instance = new T();
                        _instance.OnInit();
                    }

                    return _instance;
                }
            }
        }

        protected virtual void OnInit()
        {
        }

        protected virtual void OnDestroy()
        {
        }

        // 私有构造函数，防止外部实例化
        protected Singleton()
        {
        }

        //销毁这个单列
        public void Destroy()
        {
            _instance.OnDestroy();
            _instance = null;
        }
    }
}